import type { App } from 'vue'
import { createRouter, createWebHashHistory, RouteRecordRaw } from 'vue-router'
import Nprogress from 'nprogress'

import { initRoute } from './initRoute'
import store from '@/store'
import { message } from 'ant-design-vue'
import { installApiRoute } from '@/utils/routeHelper'
import { getItem } from '@/utils/storage'

const routes: RouteRecordRaw[] = initRoute

const router = createRouter({
  history: createWebHashHistory(),
  routes,
})

// 添加当前存储的路由
installApiRoute(router, 'home', getItem('menuList') || [])

router.beforeEach((to, from, next) => {
  Nprogress.start()
  if (to.path === '/login' && store.state.account.currentUser) {
    message.warn('您已登录，如需切换账号请先注销当前帐号！')
    next(from.path)
  } else if (!store.state.account.currentUser && to.path !== '/login') {
    message.warn('请先登录！')
    next('/login')
  } else if (!router.getRoutes().find((item) => item.path == to.path)) {
    next('/404')
  }
  next()
  document.title = `PAIXIN-${to.meta.title as string}`
})

// eslint-disable-next-line @typescript-eslint/no-unused-vars
router.afterEach((to, from, next) => {
  Nprogress.done()
})

// 配置 router
export function setupRouter(app: App<Element>) {
  app.use(router)
}

export default router
